import sqlalchemy
import pandas as pd

# 将DataFrame保存到数据库表
def saveToPg(df_pd, tbname):
    # 设置openGauss数据库版本信息
    from sqlalchemy.dialects.postgresql.base import PGDialect
    PGDialect._get_server_version_info = lambda *args: (9, 2)
    # 构造连接字符串
    userName = 'myroot'
    password = 'myroot_123'
    dbHost = '10.10.74.207'
    dbPort = 15400
    dbName = 'app'
    DB_CONNECT = f'postgresql://{userName}:{password}@{dbHost}:{dbPort}/{dbName}'
    # 创建数据库连接
    conn = sqlalchemy.create_engine(DB_CONNECT)
    if conn:
        print("连接openGauss成功")
    # 将DataFrame写入数据库
    df_pd.to_sql(tbname, conn, if_exists='replace', index=False)
    print("存储成功")

# 读取CSV函数
def readFromCSV(fname):
    # 读取 CSV 文件为 pandas DataFrame
    pandasdf = pd.read_csv(fname,encoding='utf-8')
    return pandasdf

if __name__ == '__main__':
    # 执行读取CSV的操作
    df = readFromCSV("a20230103.csv")
    # 打印CSV数据中的行数
    print(f"csv数据条数：{len(df)}")
    # 将处理后的数据保存到openGauss数据库
    saveToPg(df, "a20230103")